<!--
 * @Author: your name
 * @Date: 2020-03-26 09:41:08
 * @LastEditTime: 2020-03-26 09:41:10
 * @LastEditors: Please set LastEditors
 * @Description: 小金矿
 -->

<template>
  <div>
    <van-form class="gold-coin">
      <van-field
        v-model="ruleForm.username"
        type="tel"
        maxlength="11"
        label="账号"
        placeholder="请填写账号"
        clearable
      />
      <van-field
        v-model="ruleForm.password"
        type="password"
        label="密码"
        placeholder="请填写密码"
        clearable
      />
      <van-field v-model="IntervalTime" type="tel" label="抢单间隔(s)" placeholder="请填写抢单间隔" clearable />
      <van-field name="radio" label="任务类型">
        <template #input>
          <van-radio-group v-model="type" direction="horizontal">
            <van-radio
              v-for="(option, index) in typeOptions"
              :key="index"
              :name="option.type"
              checked-color="#e4393c"
            >{{ option.label }}</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <van-cell-group>
        <van-cell
          class="van-cell__tip"
          v-for="(content, index) in returnContent"
          :key="index"
          :title="content"
        />
      </van-cell-group>
    </van-form>
    <div class="popup-open__btn">
      <van-button type="warning">做单</van-button>
      <van-button type="danger" @click="onStart">{{ startFlag ? '停止接单' : '开始接单' }}</van-button>
    </div>
  </div>
</template>

<script>
import { alertMsg, saveInfo, audio } from "@/utils/index";
import sha1 from "js-sha1";
import md5 from "js-md5";
export default {
  name: "GoldCoin",
  props: {
    index: {
      type: String,
      default: ""
    },
    item: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      ruleForm: {
        username: "13075716220",
        password: "716220",
        device_id: window.api.deviceId,
        smscode: "1234",
        appversion: "0.1.65",
        usercontacts: ""
      },
      IntervalTime: 3,
      type: "1",
      typeOptions: [
        { label: "精刷单", type: "1" },
        { label: "隔日单", type: "2" },
        { label: "流量单", type: "3" }
      ],
      startFlag: false,
      returnContent: [],
      validuserid: "",
      time: "",
      appid: "63c11117_f407_4bb3_a0d5_31ad96b4513e",
      appkey:
        "XJK67CE7208-945da874-2a46-432b-9faa-e66ab43f3809-8B7A0526F65EXJK",
      // 已接单标记
      isAcceptSuc: false,
      activeIndex: ""
    };
  },
  watch: {
    // 监听接单状态
    startFlag() {
      if (this.item.index === 4 && this.index !== "") {
        this.$emit("changeOpened", {
          index: this.index,
          status: this.isAcceptSuc
            ? "已接单"
            : this.startFlag
            ? "已启动"
            : "待启动",
          startFlag: this.startFlag,
          content: this.returnContent
        });
      }
    },
    returnContent() {
      if (this.returnContent.length >= 10) {
        this.returnContent = this.returnContent.filter((item, i) => i < 5);
      }
    },
    // 监听当前索引
    index() {
      if (this.item.index === 4 && this.index !== "") {
        this.activeIndex = this.index;
        // 获取保存账号信息
        this.ruleForm.username = this.item.user;
        this.ruleForm.password = this.item.pass;
        this.type = this.item.type || "1";

        // 如为 已接单 => 改变状态
        if (this.item.opened === "已接单") {
          this.$emit("changeOpened", {
            index: this.index,

            status: "待启动",
            startFlag: this.startFlag,
            content: this.returnContent
          });
        }
      }
    }
  },
  created() {
    if (this.item.index === 4 && this.index !== "") {
      this.activeIndex = this.index;
      // 获取保存账号信息
      this.ruleForm.username = this.item.user;
      this.ruleForm.password = this.item.pass;
      this.type = this.item.type || "1";
    }
  },
  methods: {
    // 开始接单
    onStart() {
      const _this = this;
      if (!this.startFlag) {
        if (!/^1[3456789]\d{9}$/.test(this.ruleForm.username)) {
          this.$toast("手机号码输入有误");
          return false;
        }
        if (this.ruleForm.password === "") {
          this.$toast("密码输入有误");
          return false;
        }
        if (this.IntervalTime === "") {
          this.$toast("抢单间隔输入有误");
          return false;
        }
        // 登录 获取服务器时间
        this.returnContent = [];
        this.startFlag = true;
        this.returnContent.unshift(alertMsg("获取服务器时间"));
        this.$ajax({
          url: "https://app.h26.top/shokey/Base/gettime",
          type: "post",
          headers: {
            "X-APICloud-AppId": _this.appid,
            "X-APICloud-AppKey": "",
            system: window.api.systemType,
            appversion: "0.1.65",
            "device-id": window.api.deviceId
          },
          ajaxData: {
            values: ""
          },
          method: function(res) {
            if (res) {
              _this.time = res.time;
              _this.ruleForm.usercontacts = "";
              var contacts = window.api.require("contacts");
              contacts.queryByPage(
                {
                  pageIndex: 0
                },
                function(ret, err) {
                  if (ret) {
                    _this.ruleForm.usercontacts = ret.contacts;
                    let key =
                      sha1(_this.appid + _this.appkey + _this.time) +
                      "." +
                      _this.time;
                    let key2 = "";
                    if (key) {
                      key2 = key.substring(key.indexOf(".") + 1, key.length);
                      key2 = md5(key) + "." + key2;
                    }
                    _this.returnContent.unshift(alertMsg("正在登录"));
                    _this.$ajax({
                      url: "https://app.h26.top/shokey/login/login",
                      type: "post",
                      headers: {
                        "X-APICloud-AppId": _this.appid,
                        "X-APICloud-AppKey": key2,
                        system: window.api.systemType,
                        appversion: "0.1.65",
                        "device-id": window.api.deviceId
                      },
                      ajaxData: {
                        values: _this.ruleForm
                      },
                      method: function(res) {
                        _this.returnContent.unshift(alertMsg(res.res_msg));
                        if (res.res_code === 1) {
                          // 登录成功  => 保存账号信息
                          saveInfo({
                            user: _this.ruleForm.username,
                            pass: _this.ruleForm.password,
                            type: _this.type,
                            index: _this.index
                          });
                          _this.validuserid = res.validuserid;
                          _this.onGetList(_this);
                        } else {
                          _this.startFlag = false;
                        }
                      }
                    });
                  } else {
                    alert(JSON.stringify(err));
                  }
                }
              );
            } else {
              _this.startFlag = false;
              _this.onStart();
            }
          }
        });
      } else {
        this.returnContent.unshift(alertMsg("接单取消"));
        clearInterval(_this.timer);
        this.startFlag = false;
        this.isAcceptSuc = false;
        this.$toast({ message: "已停止接单" });
      }
    },
    // 获取任务列表
    onGetList(_this) {
      clearInterval(this.timer);
      this.$ajax({
        url: "https://app.h26.top/shokey/Base/gettime",
        type: "post",
        headers: {
          "X-APICloud-AppId": _this.appid,
          "X-APICloud-AppKey": "",
          system: window.api.systemType,
          appversion: "0.1.65",
          "device-id": window.api.deviceId
        },
        ajaxData: {
          values: ""
        },
        method: function(res) {
          _this.time = res.time;
          let key =
            sha1(_this.appid + _this.appkey + _this.time) + "." + _this.time;
          _this.$ajax({
            url: "https://app.h26.top/shokey/index/completeNumber",
            type: "post",
            dataType: "json",
            headers: {
              "X-APICloud-AppId": _this.appid,
              "X-APICloud-AppKey": key,
              system: window.api.systemType,
              appversion: "0.1.65",
              "device-id": window.api.deviceId
            },
            ajaxData: {
              values: {
                username: _this.ruleForm.username,
                validuserid: _this.validuserid,
                deviceid: window.api.deviceId
              }
            },
            method: function(res) {
              _this.returnContent.unshift(alertMsg(res.res_msg));
              if (res.res_code === 1) {
                _this.onGrabSheet();
              } else {
                _this.timer = setInterval(() => {
                  if (_this.startFlag) {
                    _this.onGetList(_this);
                  }
                }, _this.IntervalTime * 1000);
              }
            }
          });
        }
      });
    },
    // 抢单
    onGrabSheet() {
      const _this = this;
      clearInterval(this.timer);
      this.$ajax({
        url: "",
        type: "get",
        ajaxData: {},
        headers: {},
        method: function(res) {
          if (res.res_code === 1) {
            _this.returnContent.unshift(alertMsg("接单成功，请前往做单..."));
            audio();
            _this.isAcceptSuc = true;
            _this.startFlag = false;
            _this.$emit("changeOpened", {
              index: _this.activeIndex,
              status: "已接单",
              startFlag: false,
              content: ["接单成功，请前往做单..."]
            });
          } else {
            _this.timer = setInterval(() => {
              if (_this.startFlag) {
                _this.onGrabSheet();
              }
            }, _this.IntervalTime * 1000);
          }
        }
      });
    }
  }
};
</script>
